package com.superpet.common;

import java.sql.Connection;

import com.superpet.common.intercept.ApiIntercept;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.superpet.common.model._MappingKit;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.template.Engine;

public class MainConfig extends JFinalConfig {

	public static String proFileName = "app_config.txt";
	public static String uploadpath;
	private WallFilter wallFilter;

	public void configConstant(Constants me) {
		PropKit.use(proFileName);
		me.setDevMode(PropKit.getBoolean("devMode", false));
		me.setJsonFactory(MixedJsonFactory.me());
		uploadpath = PropKit.get("uploadpath");
		if (StringUtils.isBlank(uploadpath)) {// 为空则表示本地测试，使用工程目录
			uploadpath = PathKit.getWebRootPath();
		}
		me.setBaseUploadPath(uploadpath);
	}
	
	public void configRoute(Routes me) {
		me.add(new ApiRoutes());
	}
	
    public void configEngine(Engine me) {
    }
	
	public static DruidPlugin getDruidPlugin() {
		return new DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password").trim());
	}
	
    public void configPlugin(Plugins me) {
	    DruidPlugin druidPlugin = getDruidPlugin();
	    wallFilter = new WallFilter();
	    wallFilter.setDbType("mysql");
	    druidPlugin.addFilter(wallFilter);
	    me.add(druidPlugin);
	    
	    ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
	    arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
	    _MappingKit.mapping(arp);
	    me.add(arp);
        if (PropKit.getBoolean("devMode", false)) {
            arp.setShowSql(true);
        }
        arp.setBaseSqlTemplatePath(PathKit.getRootClassPath() + "/sql");
        arp.addSqlTemplate("all_sqls.sql");
        
	    me.add(new EhCachePlugin());
    }
	
	public void configInterceptor(Interceptors me) {
		me.add(new ApiIntercept());
	}
	
	public void configHandler(Handlers me) {
	}
	
	public void afterJFinalStart() {
		wallFilter.getConfig().setSelectUnionCheck(false);
	}
	
	public static void main(String[] args) {
		JFinal.start("src/main/webapp", 80, "/");
	}
	
}
